package LifeForms;

import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;

import Game.Entity;
import Game.Mainth;
import Game.Sprite;
import Guns.Cal45;
import Guns.Projectile;

public class Turret extends Entity{
	private boolean a;
	private boolean d;
	private Cal45 gun;
	private boolean clear; 
	private long orgTime;
	public Turret(Robot robot,Sprite sprite, int ID, int x, int y) {
		super(sprite, ID, x, y);
		gun=new Cal45(robot);
	}
	public void retreiveX(Robot robot){
		this.x=robot.getX();
	}
	public void retreiveY(Robot robot){
		this.y=robot.getY();
	}
	public void control(ArrayList<Projectile> projectiles,Robot robot){
		if(robot.toggle){
			if(a){
				angle-=1;
			}if(d){
				angle+=1;
			}
			if(Mainth.spaceBar&&clear){
				gun.fire(robot,projectiles);
				clear=false;
				orgTime=System.currentTimeMillis();
			}
			if(!clear){
				if(orgTime+100<=System.currentTimeMillis()){
					clear=true;
				}
			}
		}
	}
	public double getfireSpeedX(){
		int sub=0;
		int div=90;
		if(angle>=0&&angle<180){
			if(angle<90){
				sub=0;
				div=90;
			}else if(angle<180){
				sub=180;
				div=90;
			}
		}else if(angle>=180&&angle<360){
			if(angle<270){
				sub=180;
				div=-90;
			}else if(angle<360){
				sub=360;
				div=-90;
			}
		}
		
		return ((double)(Math.abs(angle-sub))/div);
	}
	public double getfireSpeedY(){
		int sub=0;
		int div=90;
		if(angle>=90&&angle<270){
			if(angle<180){
				sub=90;
				div=90;
			}else if(angle<270){
				sub=270;
				div=-90;
			}
		}else if(angle>=270||angle<90){
			if(angle<90){
				sub=90;
				div=90;
			}else if(angle<360){
				sub=270;
				div=-90;
			}
		}
		return ((double)(angle-sub)/div);
	}
	public void update(Robot robot){
		this.a=Mainth.a;
		this.d=Mainth.d;
		retreiveX(robot);
		retreiveY(robot);
		if(angle>=360){
			angle-=360;
		}
		if(angle<0){
			angle+=360;
		}
		this.gun.update(robot);
	}
	public void paint(Graphics2D g2d,int Index,int x,int y){
		this.Draw(g2d,0,0,0);
		AffineTransform tfm = new AffineTransform();
        tfm.rotate(Math.toRadians(this.angle),this.x+(this.getSprite().getWidth()/2),this.y+(this.getSprite().getHeight()/2));
        g2d.setTransform(tfm);
        this.Draw(g2d,0,0,0);
        tfm.rotate(Math.toRadians(-this.angle),this.x+(this.getSprite().getWidth()/2),this.y+(this.getSprite().getHeight()/2));
        g2d.setTransform(tfm);
	}
}
